from ast import literal_eval


def is_search_param(item):
    """
    Filter search params
    """
    if item[0].startswith("search_"):
        return True
    return False


def get_search_param(item):
    return (item[0][7:], item[1])


def list_string(value):
    """[将列表字符串转列表]

    Args:
        value ([str]): [列表字符串]

    Returns:
        [list]: [返回列表]
    """
    if value.find("[") == 0 and value.find("]") == len(value)-1:
        value = literal_eval(value)
    return value


def search_decorator(f):
    """
    decorate get_queryset method
    do further filtering
    URL carries param: search_QUERY
    QUERY is a string follows query rule of Django model
    """

    def wrapper(*args, **kwargs):
        queryset = f(*args, **kwargs)
        items = args[0].request.query_params.items()
        items = filter(is_search_param, items)
        search_items = map(get_search_param, items)
        search_dict = {key: list_string(value) for key, value in search_items}
        try:
            if len(search_dict) > 0:
                queryset = queryset.filter(**search_dict)
        except Exception as e:
            print(e)
        return queryset

    return wrapper
